package com.ncu.web.filter;

import com.alibaba.fastjson.JSONObject;
import com.ncu.web.util.Code;
import com.ncu.web.util.JWTUtil;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @Author:大润发杀鱼匠
 * @Date:2024/5/26 20:36 web
 */

@WebFilter(filterName = "LoginFilter", urlPatterns = {"/*"})
public class LoginFilter extends OncePerRequestFilter {

    @Autowired
    private JWTUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String requestURI = request.getRequestURI();

        if ("/majority/get/all".equals(requestURI)) {

        } else if ((!"/user/login".equals(requestURI)) && (!"/user/register".equals(requestURI))) {


            final String header = request.getHeader("Authorization");

            if (header != null && header.startsWith("Bearer ")) {
                // 从Authorization头中提取JWT令牌
                String token = header.substring(7);
                if (!jwtUtil.validateToken(token)) {
                    String username = jwtUtil.parseToken(token).getBody().get("username", String.class);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("code", Code.NOT_LOGIN);
                    jsonObject.put("msg", "登录过期");
                    jsonObject.put("username", username);
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().write(jsonObject.toJSONString());
                    return;
                }

            } else {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", Code.NOT_LOGIN);
                jsonObject.put("msg", "用户未登录");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(jsonObject.toJSONString());
                return;
            }
        }

        filterChain.doFilter(request, response);
    }
}